import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
import type { API } from '../../src/types/api/response'
import type { DictType, DictTypeQuery, CreateDictType, UpdateDictType, DictTypeList } from '../../src/types/api/config/dictType'
import type { DictData, DictDataQuery, CreateDictData, UpdateDictData, DictDataList } from '../../src/types/api/config/dictData'

const Random = Mock.Random

// ------------ 常量定义 ------------
const dictStatuses = [
  { value: '0', label: '正常' },
  { value: '1', label: '停用' }
]

// 预定义真实的字典类型
const realDictTypes = [
  {
    dictName: '用户性别',
    dictType: 'sys_user_sex',
    values: [
      { label: '男', value: 'male', sort: 1, cssClass: 'primary' },
      { label: '女', value: 'female', sort: 2, cssClass: 'danger' },
      { label: '未知', value: 'unknown', sort: 3, cssClass: 'info' }
    ]
  },
  {
    dictName: '菜单状态',
    dictType: 'sys_menu_status',
    values: [
      { label: '显示', value: 'show', sort: 1, cssClass: 'primary' },
      { label: '隐藏', value: 'hide', sort: 2, cssClass: 'info' }
    ]
  },
  {
    dictName: '系统开关',
    dictType: 'sys_switch',
    values: [
      { label: '开启', value: 'on', sort: 1, cssClass: 'success' },
      { label: '关闭', value: 'off', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '任务状态',
    dictType: 'sys_job_status',
    values: [
      { label: '正常', value: 'normal', sort: 1, cssClass: 'primary' },
      { label: '暂停', value: 'pause', sort: 2, cssClass: 'warning' }
    ]
  },
  {
    dictName: '系统是否',
    dictType: 'sys_yes_no',
    values: [
      { label: '是', value: 'yes', sort: 1, cssClass: 'primary' },
      { label: '否', value: 'no', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '通知类型',
    dictType: 'sys_notice_type',
    values: [
      { label: '通知', value: 'notification', sort: 1, cssClass: 'primary' },
      { label: '公告', value: 'announcement', sort: 2, cssClass: 'success' }
    ]
  },
  {
    dictName: '通知状态',
    dictType: 'sys_notice_status',
    values: [
      { label: '正常', value: 'normal', sort: 1, cssClass: 'primary' },
      { label: '关闭', value: 'closed', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '操作类型',
    dictType: 'sys_oper_type',
    values: [
      { label: '新增', value: 'add', sort: 1, cssClass: 'primary' },
      { label: '修改', value: 'update', sort: 2, cssClass: 'info' },
      { label: '删除', value: 'delete', sort: 3, cssClass: 'danger' },
      { label: '查询', value: 'query', sort: 4, cssClass: 'success' },
      { label: '导出', value: 'export', sort: 5, cssClass: 'warning' },
      { label: '导入', value: 'import', sort: 6, cssClass: 'warning' },
      { label: '强退', value: 'force_quit', sort: 7, cssClass: 'danger' },
      { label: '清空数据', value: 'clean', sort: 8, cssClass: 'danger' }
    ]
  },
  {
    dictName: '日志状态',
    dictType: 'sys_log_status',
    values: [
      { label: '成功', value: 'success', sort: 1, cssClass: 'success' },
      { label: '失败', value: 'fail', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '数据状态',
    dictType: 'data_status',
    values: [
      { label: '正常', value: 'normal', sort: 1, cssClass: 'primary' },
      { label: '停用', value: 'disabled', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '登录状态',
    dictType: 'sys_login_status',
    values: [
      { label: '成功', value: 'success', sort: 1, cssClass: 'success' },
      { label: '失败', value: 'fail', sort: 2, cssClass: 'danger' }
    ]
  },
  {
    dictName: '账号状态',
    dictType: 'sys_user_status',
    values: [
      { label: '正常', value: 'normal', sort: 1, cssClass: 'primary' },
      { label: '停用', value: 'disabled', sort: 2, cssClass: 'danger' },
      { label: '锁定', value: 'locked', sort: 3, cssClass: 'warning' }
    ]
  },
  {
    dictName: '文件类型',
    dictType: 'sys_file_type',
    values: [
      { label: '图片', value: 'image', sort: 1, cssClass: 'primary' },
      { label: '文档', value: 'document', sort: 2, cssClass: 'info' },
      { label: '视频', value: 'video', sort: 3, cssClass: 'success' },
      { label: '音频', value: 'audio', sort: 4, cssClass: 'warning' },
      { label: '其他', value: 'other', sort: 5, cssClass: 'danger' }
    ]
  },
  {
    dictName: '系统优先级',
    dictType: 'sys_priority',
    values: [
      { label: '低', value: 'low', sort: 1, cssClass: 'info' },
      { label: '中', value: 'medium', sort: 2, cssClass: 'primary' },
      { label: '高', value: 'high', sort: 3, cssClass: 'warning' },
      { label: '紧急', value: 'urgent', sort: 4, cssClass: 'danger' }
    ]
  },
  {
    dictName: '业务状态',
    dictType: 'biz_status',
    values: [
      { label: '进行中', value: 'in_progress', sort: 1, cssClass: 'primary' },
      { label: '已完成', value: 'completed', sort: 2, cssClass: 'success' },
      { label: '已取消', value: 'cancelled', sort: 3, cssClass: 'danger' },
      { label: '已暂停', value: 'paused', sort: 4, cssClass: 'warning' }
    ]
  }
]

// ------------ 工具函数 ------------
/**
 * 生成字典类型
 */
const generateDictType = (id: string, dictTypeData: any): DictType => {
  const status = dictStatuses[Math.floor(Math.random() * 10) > 2 ? 0 : 1] // 大部分为正常状态
  return {
    id,
    dictName: dictTypeData.dictName,
    dictType: dictTypeData.dictType,
    status: status.value as '0' | '1',
    createTime: new Date(Date.now() - Math.floor(Math.random() * 60 * 86400000)).toISOString().split('T')[0] + ' ' + 
                new Date().toTimeString().split(' ')[0],
    remark: `${dictTypeData.dictName}字典，用于系统${dictTypeData.dictName}选项`
  }
}

/**
 * 生成字典数据
 */
const generateDictData = (id: string, typeData: any, valueData: any): DictData => {
  const status = dictStatuses[Math.floor(Math.random() * 10) > 2 ? 0 : 1]
  return {
    id,
    dictId: typeData.id,
    dictType: typeData.dictType,
    dictLabel: valueData.label,
    dictValue: valueData.value,
    dictSort: valueData.sort,
    status: status.value as '0' | '1',
    cssClass: valueData.cssClass,
    remark: `${valueData.label}选项`
  }
}

// ------------ 模拟数据 ------------
// 生成字典类型数据
const dictTypes: DictType[] = realDictTypes.map((type, index) => 
  generateDictType(String(index + 1), type)
)

// 生成字典数据
const dictData: DictData[] = []
let dataId = 1
realDictTypes.forEach((type, typeIndex) => {
  type.values.forEach((value, valueIndex) => {
    dictData.push(generateDictData(`${typeIndex + 1}-${valueIndex + 1}`, type, value))
    dataId++
  })
})

// ------------ API 实现 ------------
/**
 * 获取字典类型列表
 */
const getDictTypeListApi: MockMethod = {
  url: '/api/config/dict/type/list',
  method: 'get',
  response: ({ query }: { query: DictTypeQuery }): API.Response<DictTypeList> => {
    const { dictName, dictType, status, pageNum = 1, pageSize = 10 } = query
    
    // 确保 page 和 pageSize 是数字类型
    const pageNumValue = Number(pageNum)
    const pageSizeValue = Number(pageSize)
    
    let filteredDictTypes = [...dictTypes]

    if (dictName) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictName.includes(dictName) || type.dictType.includes(dictName)
      )
    }

    if (dictType) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictType.includes(dictType) || type.dictType.includes(dictType)
      )
    }

    if (status) {
      filteredDictTypes = filteredDictTypes.filter(type => type.status === status)
    }

    const startIndex = (pageNumValue - 1) * pageSizeValue
    const endIndex = startIndex + pageSizeValue
    const list = filteredDictTypes.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredDictTypes.length
      }
    }
  }
}

/**
 * 获取字典类型分页列表
 */
const getDictTypePageApi: MockMethod = {
  url: '/api/config/dict/type/page',
  method: 'get',
  response: ({ query }: { query: DictTypeQuery }): API.Response<API.PageResult<DictType>> => {
    const { dictName, dictType, status, page = 1, pageSize = 10 } = query
    
    // 确保 page 和 pageSize 是数字类型
    const pageNum = Number(page)
    const pageSizeNum = Number(pageSize)
    
    let filteredDictTypes = [...dictTypes]

    if (dictName) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictName.includes(dictName)
      )
    }

    if (dictType) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictType.includes(dictType)
      )
    }

    if (status) {
      filteredDictTypes = filteredDictTypes.filter(type => type.status === status)
    }

    const startIndex = (pageNum - 1) * pageSizeNum
    const endIndex = startIndex + pageSizeNum
    const list = filteredDictTypes.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredDictTypes.length,
        page: typeof pageNum === 'string' ? parseInt(pageNum) : pageNum,
        pageSize: typeof pageSize === 'string' ? parseInt(pageSize) : pageSize
      }
    }
  }
}

/**
 * 获取字典类型详情
 */
const getDictTypeDetailApi: MockMethod = {
  url: '/api/config/dict/type/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<DictType | null> => {
    const dictType = dictTypes.find(item => item.id === query.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: dictType || null
    }
  }
}

/**
 * 创建字典类型
 */
const createDictTypeApi: MockMethod = {
  url: '/api/config/dict/type',
  method: 'post',
  response: ({ body }: { body: CreateDictType }): API.Response<DictType | null> => {
    const { dictName, dictType, status, remark } = body

    // 检查字典类型是否已存在
    if (dictTypes.some(item => item.dictType === dictType)) {
      return {
        code: 400,
        success: false,
        message: '字典类型已存在',
        data: null
      }
    }

    const newDictType: DictType = {
      id: String(dictTypes.length + 1),
      dictName,
      dictType,
      status,
      createTime: new Date().toISOString(),
      remark: remark || ''
    }

    dictTypes.push(newDictType)
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newDictType
    }
  }
}

/**
 * 更新字典类型
 */
const updateDictTypeApi: MockMethod = {
  url: '/api/config/dict/type/:id',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: UpdateDictType }): API.Response<null> => {
    const index = dictTypes.findIndex(item => item.id === query.id)
    if (index > -1) {
      const { dictName, dictType, status, remark } = body

      // 检查字典类型是否已存在（排除自身）
      if (dictTypes.some(item => item.id !== query.id && item.dictType === dictType)) {
        return {
          code: 400,
          success: false,
          message: '字典类型已存在',
          data: null
        }
      }

      dictTypes[index] = {
        ...dictTypes[index],
        dictName,
        dictType,
        status,
        remark: remark || ''
      }
    }

    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除字典类型
 */
const deleteDictTypeApi: MockMethod = {
  url: '/api/config/dict/type/:id',
  method: 'delete',
  response: ({ query }: { query: { id: string } }): API.Response<null> => {
    const index = dictTypes.findIndex(item => item.id === query.id)
    if (index > -1) {
      // 检查是否有关联的字典数据
      if (dictData.some(item => item.dictType === dictTypes[index].dictType)) {
        return {
          code: 400,
          success: false,
          message: '该字典类型下存在字典数据，不能删除',
          data: null
        }
      }
      dictTypes.splice(index, 1)
    }

    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 批量删除字典类型
 */
const batchDeleteDictTypeApi: MockMethod = {
  url: '/api/config/dict/type',
  method: 'delete',
  response: ({ body }: { body: { ids: string[] } }): API.Response<null> => {
    const { ids } = body
    
    // 检查是否有关联的字典数据
    for (const id of ids) {
      const dictType = dictTypes.find(item => item.id === id)
      if (dictType && dictData.some(item => item.dictType === dictType.dictType)) {
        return {
          code: 400,
          success: false,
          message: `字典类型"${dictType.dictName}"下存在字典数据，不能删除`,
          data: null
        }
      }
    }
    
    // 执行批量删除
    let deletedCount = 0
    for (const id of ids) {
      const index = dictTypes.findIndex(item => item.id === id)
      if (index > -1) {
        dictTypes.splice(index, 1)
        deletedCount++
      }
    }
    
    return {
      code: 200,
      success: true,
      message: `成功删除 ${deletedCount} 个字典类型`,
      data: null
    }
  }
}

/**
 * 导出字典类型
 */
const exportDictTypeApi: MockMethod = {
  url: '/api/config/dict/type/export',
  method: 'get',
  response: ({ query }: { query: DictTypeQuery }): BlobPart => {
    const { dictName, dictType, status } = query
    let filteredDictTypes = [...dictTypes]
    
    if (dictName) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictName.includes(dictName)
      )
    }
    
    if (dictType) {
      filteredDictTypes = filteredDictTypes.filter(
        type => type.dictType.includes(dictType)
      )
    }
    
    if (status) {
      filteredDictTypes = filteredDictTypes.filter(type => type.status === status)
    }
    
    // 为了mock返回，这里只返回一个字符串
    // 实际上应该返回一个二进制blob，但这超出了mock的范围
    return 'Mock Excel Data for Dictionary Types Export'
  }
}

/**
 * 获取字典数据列表
 */
const getDictDataListApi: MockMethod = {
  url: '/api/config/dict/data/list',
  method: 'get',
  response: ({ query }: { query: DictDataQuery }): API.Response<DictDataList> => {
    const { dictType, dictLabel, status, pageNum = 1, pageSize = 10 } = query
    let filteredDictData = [...dictData]

    if (dictType) {
      filteredDictData = filteredDictData.filter(data => data.dictType === dictType)
    }

    if (dictLabel) {
      filteredDictData = filteredDictData.filter(
        data => data.dictLabel.includes(dictLabel) || data.dictValue.includes(dictLabel)
      )
    }

    if (status) {
      filteredDictData = filteredDictData.filter(data => data.status === status)
    }

    const startIndex = (pageNum - 1) * pageSize
    const endIndex = startIndex + pageSize
    const list = filteredDictData.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredDictData.length
      }
    }
  }
}

/**
 * 获取字典数据分页列表
 */
const getDictDataPageApi: MockMethod = {
  url: '/api/config/dict/data/page',
  method: 'get',
  response: ({ query }: { query: DictDataQuery }): API.Response<API.PageResult<DictData>> => {
    const { dictType, dictLabel, status, pageNum = 1, pageSize = 10 } = query
    let filteredDictData = [...dictData]

    if (dictType) {
      filteredDictData = filteredDictData.filter(data => data.dictType === dictType)
    }

    if (dictLabel) {
      filteredDictData = filteredDictData.filter(
        data => data.dictLabel.includes(dictLabel) || data.dictValue.includes(dictLabel)
      )
    }

    if (status) {
      filteredDictData = filteredDictData.filter(data => data.status === status)
    }

    const startIndex = (pageNum - 1) * pageSize
    const endIndex = startIndex + pageSize
    const list = filteredDictData.slice(startIndex, endIndex)

    return {
      code: 200,
      success: true,
      message: 'ok',
      data: {
        list,
        total: filteredDictData.length,
        page: typeof pageNum === 'string' ? parseInt(pageNum) : pageNum,
        pageSize: typeof pageSize === 'string' ? parseInt(pageSize) : pageSize
      }
    }
  }
}

/**
 * 获取字典数据详情
 */
const getDictDataDetailApi: MockMethod = {
  url: '/api/config/dict/data/:id',
  method: 'get',
  response: ({ query }: { query: { id: string } }): API.Response<DictData | null> => {
    const data = dictData.find(item => item.id === query.id)
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: data || null
    }
  }
}

/**
 * 创建字典数据
 */
const createDictDataApi: MockMethod = {
  url: '/api/config/dict/data',
  method: 'post',
  response: ({ body }: { body: CreateDictData }): API.Response<DictData | null> => {
    const { dictType, dictLabel, dictValue, dictSort, status, cssClass, remark } = body

    // 检查字典数据是否已存在
    if (dictData.some(item => item.dictType === dictType && item.dictValue === dictValue)) {
      return {
        code: 400,
        success: false,
        message: '字典数据已存在',
        data: null
      }
    }

    const newDictData: DictData = {
      id: String(dictData.length + 1),
      dictType,
      dictLabel,
      dictValue,
      dictSort,
      status,
      cssClass: cssClass || '',
      remark: remark || ''
    }

    dictData.push(newDictData)
    return {
      code: 200,
      success: true,
      message: '创建成功',
      data: newDictData
    }
  }
}

/**
 * 更新字典数据
 */
const updateDictDataApi: MockMethod = {
  url: '/api/config/dict/data/:id',
  method: 'put',
  response: ({ query, body }: { query: { id: string }; body: UpdateDictData }): API.Response<null> => {
    const index = dictData.findIndex(item => item.id === query.id)
    if (index > -1) {
      const { dictType, dictLabel, dictValue, dictSort, status, cssClass, remark } = body

      // 检查字典数据是否已存在（排除自身）
      if (dictData.some(item => item.id !== query.id && item.dictType === dictType && item.dictValue === dictValue)) {
        return {
          code: 400,
          success: false,
          message: '字典数据已存在',
          data: null
        }
      }

      dictData[index] = {
        ...dictData[index],
        dictType,
        dictLabel,
        dictValue,
        dictSort,
        status,
        cssClass: cssClass || '',
        remark: remark || ''
      }
    }

    return {
      code: 200,
      success: true,
      message: '更新成功',
      data: null
    }
  }
}

/**
 * 删除字典数据
 */
const deleteDictDataApi: MockMethod = {
  url: '/api/config/dict/data/:id',
  method: 'delete',
  response: ({ query }: { query: { id: string } }): API.Response<null> => {
    const index = dictData.findIndex(item => item.id === query.id)
    if (index > -1) {
      dictData.splice(index, 1)
    }

    return {
      code: 200,
      success: true,
      message: '删除成功',
      data: null
    }
  }
}

/**
 * 批量删除字典数据
 */
const batchDeleteDictDataApi: MockMethod = {
  url: '/api/config/dict/data',
  method: 'delete',
  response: ({ body }: { body: { ids: string[] } }): API.Response<null> => {
    const { ids } = body
    let deletedCount = 0
    
    for (const id of ids) {
      const index = dictData.findIndex(item => item.id === id)
      if (index > -1) {
        dictData.splice(index, 1)
        deletedCount++
      }
    }
    
    return {
      code: 200,
      success: true,
      message: `成功删除 ${deletedCount} 个字典数据`,
      data: null
    }
  }
}

/**
 * 根据字典类型获取字典数据
 */
const getDictDataByTypeApi: MockMethod = {
  url: '/api/config/dict/data/type/:dictType',
  method: 'get',
  response: ({ query }: { query: { dictType: string } }): API.Response<DictData[]> => {
    const { dictType } = query
    const filteredDictData = dictData.filter(data => data.dictType === dictType)
    
    // 按照dictSort排序
    filteredDictData.sort((a, b) => a.dictSort - b.dictSort)
    
    return {
      code: 200,
      success: true,
      message: 'ok',
      data: filteredDictData
    }
  }
}

// ------------ 导出 ------------
export default [
  getDictTypeListApi,
  getDictTypePageApi,
  getDictTypeDetailApi,
  createDictTypeApi,
  updateDictTypeApi,
  deleteDictTypeApi,
  batchDeleteDictTypeApi,
  exportDictTypeApi,
  getDictDataListApi,
  getDictDataPageApi,
  getDictDataDetailApi,
  createDictDataApi,
  updateDictDataApi,
  deleteDictDataApi,
  batchDeleteDictDataApi,
  getDictDataByTypeApi
] as MockMethod[] 